<?php
namespace app\api\controller\foodcash;

use app\api\controller\foodcash\Controller;
use app\api\model\foodcash\Order as OrderModel;
use app\api\model\foodcash\Cart as CartModel;
use app\api\model\foodcash\User as UserModel;
use app\api\model\foodcash\Goods as GoodsModel;
//use app\api\model\food\Flavor as FlavorModel;
use app\api\model\foodcash\Table as TableModel;
use app\api\model\Record as RecordModel;
use app\api\model\Setting;
use app\api\model\Device;
use hema\wechat\Pay as WxPay;
use hema\Helper;
use hema\delivery\Driver as Delivery;
use think\facade\Cache;

/**
 * 商户订单管理
 */
class Order extends Controller
{
    /**
     * 配送订单
     */
    public function peisong()
    {
		$data = $this->request->post();
        $model = OrderModel::detail($data['order_id']);
        if($model->setDelivery($data['company'],$data['shop_clerk_id'])) {
			return $this->renderMsg('配送成功');
		}
        $error = $model->getError() ?: '配送失败';
		return $this->renderError($error); 
    }
    
    /**
     * 预发布配送订单
     */
    public function preOrder($company,$order_id)
    {
		$order = OrderModel::detail($order_id);
		$dv = new Delivery($company,$order);
		if($result = $dv->preOrder()){
            $detail = $result;
            return $this->renderSuccess(compact('detail'));
        }
		return $this->renderError($dv->getError());
    }
    
    /**
     * 获取配送平台设置
     */
    public function company()
    {
        $company = Setting::getItem('webdelivery',0);
        return $this->renderSuccess(compact('company'));
    }
    
    /**
     * 叫号取餐
     */
    public function spk($order_id)
    {
        $model = OrderModel::detail($order_id);
        Device::push($model['shop_id'],'rows',$model['row_no']);
        return $this->renderMsg('操作成功');
    }
    
     /**
     * 退款操作
     */
    public function refund($order_id,$is_refund)
    {
        $model = OrderModel::detail($order_id);
        if ($model->refund($is_refund)) {
            return $this->renderMsg('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }
    
    /**
     * 确认收货 - 清台
     */
    public function receipt($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->receipt()) {
            return $this->renderMsg('操作成功');
        }
		$error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 取消已经推送的外卖订单
     */
    public function cancelDelivery($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->cancelDelivery()) {
            return $this->renderMsg('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 确认收到用户付款
     */
    public function collection($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->collection()) {
            return $this->renderMsg('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }
     /**
     * 确认发货
     */
    public function delivery($order_id,$company='')
    {
        $model = OrderModel::detail($order_id);
        if ($model->setDelivery($company)) {
            return $this->renderMsg('操作完成');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }
    
    /**
     * 确认接单
     */
    public function shop($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->setShopStatus()) {
            return $this->renderMsg('操作完成');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }
    
    /**
     * 订单详情信息
     */
    public function detail($order_id)
    {
        if($detail = OrderModel::detail($order_id)){
        	return $this->renderSuccess(compact('detail'));
        }
        return $this->renderError('订单获取失败');
    }
    
    /**
     * 订单列表
     */
    public function lists($dataType)
    {
        $model = new OrderModel;
		if($list = $model->getList($dataType,$this->shop_id)){
        	return $this->renderSuccess(compact('list'));
        }
        return $this->renderError('订单列表获取失败');
    }
    
    /**
     * 订单列表
     */
    public function all()
    {
        $model = new OrderModel;
		$list = [
			0 => $model->getList('all',$this->shop_id),
			1 => $model->getList('shop',$this->shop_id),
			2 => $model->getList('delivery',$this->shop_id),
			3 => $model->getList('collection',$this->shop_id),
			4 => $model->getList('receipt',$this->shop_id),
			5 => $model->getList('refund10',$this->shop_id),
		];
        return $this->renderSuccess(compact('list'));
    }
    
    /**
     * 订单确认-购物车结算
	 * 店内就餐参数 $people=就餐人数,$ware_price=餐具调料费,$order_pay_price=0
	 * $message=买家留言
     */
    public function cart($order_mode,$table_id=0,$people=0)
    {	
        // 商品结算信息
        $model = new OrderModel;
        $order = $model->getCart($this->user['user_id'],$this->shop_id,$order_mode);
        if($order_mode == 10 AND $table_id > 0){
            $table = TableModel::get($table_id);
        	//餐桌状态是否正常
    		if($table['status']['value'] == 20){
    		    $order['is_order'] = 0;//加单
    			$order['table_name'] = $table['table_name'] . '（加单）';
    		}else{
    		    $order['is_order'] = 1;//点单
    		    $order['table_name'] = $table['table_name'] . '（点单）';
        		//餐桌容纳人数
        		if($table['people'] < $people){
        			return $this->renderError('该（包间/餐桌）只能容纳'.$table['people'].'人');
        		}
        		//最低消费
        		if($table['consume'] > $order['order_pay_price']){
        			return $this->renderError('该（包间/餐桌）未达到最低消费￥'.$table['consume'].'元');
        		}
        		//计算所需餐具调料费
        		if($table['ware_price']>0){
        			$order['ware_price'] = Helper::number2($table['ware_price'] * $people);
        			$order['order_pay_price'] = Helper::number2($order['order_pay_price']+$order['ware_price']);
        		}
    		}
        }
        if (!$this->request->isPost()) {
            return $this->renderSuccess($order);
        }
        $data = $this->request->post();
		//判断是否是会员			
        if(empty($data['user_id'])){
        	$order['user_id'] = $this->user['user_id'];
        }else{
        	$order['user_id'] = $data['user_id'];
        }
        //堂食
        if($data['order_mode']==10 AND $data['table_id'] > 0){
    		//扫码
    		$order['table_id'] = $data['table_id'];
			$order['people'] = $data['people'];
        }else{
        	//排号
        	$order['row_no'] = row_no($this->applet_id,$this->shop_id);
        }
        //如果是外卖
        if($data['order_mode']==20){
            $order['address'] = json_encode($data['address'],true);
        }
        //自取订单计算到店时间
		if($data['order_mode']==30){
		    empty($data['arrive_time']) && $data['arrive_time'] = 0;
			$order['arrive_time'] = time() + $data['arrive_time'] * 60;
		}
		$order['order_no'] = order_no();
        $order['total_price'] = $order['order_total_price'];
        $order['pay_price'] = Helper::number2($order['order_pay_price']);   //实付金额
        $order['source'] = 20; //代客点餐
        $order['pay_status'] = 10;
        $order['pay_time'] = time();
		$order['order_mode'] = $data['order_mode'];
		$order['message'] = $data['message'];
		$order['shop_id'] = $this->shop_id;
		$order['applet_id'] = $this->applet_id;
		
		// 订单商品列表
        $goodsList = [];
        foreach ($order['goods_list'] as $goods) {
            /* @var Goods $goods */
            $goodsList[] = [
                'user_id' => $order['user_id'],
                'applet_id' => $order['applet_id'],
                'goods_id' => $goods['goods_id'],
                'goods_name' => $goods['goods_name'],
                'image_id' => isset($goods['goods_sku']['image']['url'])?$goods['goods_sku']['image_id']:$goods['image'][0]['image_id'],
                'spec_type' => $goods['spec_type'],
                'spec_sku_id' => $goods['goods_sku']['spec_sku_id'],
                'goods_spec_id' => $goods['goods_sku']['goods_spec_id'],
                'goods_attr' => $goods['goods_sku']['goods_attr'],
                'content' => $goods['content'],
                'goods_price' => $goods['goods_sku']['goods_price'],
                'line_price' => $goods['goods_sku']['line_price'],
                'total_num' => $goods['total_num'],
                'total_price' => $goods['total_price']
            ];
        }
        $order['goodsList'] = $goodsList;
       
		//用户付款
		if($data['pay_mode']==0){
            $divide = false;//分账状态
            //验证外卖订单是否要分账配送费
            if($order['order_mode'] == 20){
                $webdelivery = Setting::getItem('webdelivery',0);
                //验证配送是否开启分账
                if($webdelivery['uu']['is_open'] == 1 AND $webdelivery['uu']['pay_mode'] == 1){
                    $divide = true;
                }
                if($webdelivery['make']['is_open'] == 1 AND $webdelivery['make']['pay_mode'] == 1){
                    $divide = true;
                }
                if($webdelivery['dada']['is_open'] == 1 AND $webdelivery['make']['pay_mode'] == 1){
                    $divide = true;
                }
            }
            //获取小程序配置的支付参数
            $payment = Setting::getItem('payment');
            $wxpay = new WxPay($payment['wx']);
            if($transaction_id = $wxpay->unifiedorder($order['order_no'],$order['pay_price'],'micropay','','订单支付',$divide,$data['wx_id'])){
                $order['transaction_id'] = $transaction_id;
                $order['pay_status'] = 20;// 支付状态
                /*if($divide){
                    //开始分账 -- 待开发
                }*/
            }
        }
        //发起余额支付
        if($data['pay_mode']==1){
            $user = UserModel::get($order['user_id']);
            if($user['money'] < $order['pay_price']){
                return $this->renderError('会员账户余额不足');
            }
            $user->money = ['dec',$order['pay_price']];//扣除余额
            $user->pay = ['inc', $order['pay_price']];//增加消费金额
            $user->score = ['inc', $order['pay_price']];//增加消费积分
            $user->save();
            $order['pay_status'] = 20;// 支付状态
            //新增余额消费记录
            $record = new RecordModel;
            $record->add($order,40);
        }
        //发起后付款
        if($data['pay_mode']==2){
            $order['pay_status'] = 30;// 支付状态
        }
        //现金付款
        if($data['pay_mode']==3){
            $order['pay_status'] = 20;// 支付状态
        }
        //如果付款操作成功
        if($order['pay_status'] > 10){
            // 更新商品库存、销量
            $goods = new GoodsModel;
            $goods->updateStockSales($order['goodsList']);
            //商家是否自动接单
            if($this->user['shop']['is_order']['value'] == 1){
                $order['shop_status'] = 20;
                $order['shop_time'] = time();
                /*
                //外卖自动推送订单
                if($order['order_mode']==20 AND $this->shop['is_delivery']['value'] == 1){
                    if(!$this->setDelivery($this->shop['delivery'])){
                       return false;
                    }
                }
                */
            }
            // 创建订单
            if (!$model->add($order)) {
    			$error = $model->getError() ?: '订单创建失败';
    			return $this->renderError($error);  
            }
            $order_detail = OrderModel::detail($model['order_id']);
            $Card = new CartModel($this->user['user_id'],$this->shop_id);
		    $Card->clearAll();
            Device::push($this->shop_id,'new');//新订单提醒
            Device::print($order_detail);//打印订单
            sand_new_order_msg($order_detail);//发送模板消息 - 使用公众号
        }else{
            Cache::set('foodcash_order_' . $order['order_no'], $order, 86400);
        }
        return $this->renderSuccess([
            'pay_status' => $order['pay_status'],
            'order_no' => $order['order_no']
        ]);
    }
    
    /**
     * 检测微信支付状态
     */
    public function checkPayStatus($order_no)
    {
		if($order = Cache::get($order_no)){
            //获取小程序配置的支付参数
            $payment = Setting::getItem('payment');
            $wxpay = new WxPay($payment['wx']);
            $res = $wxpay->orderquery($order['order_no']);
            if($res != 'SUCCESS'){
                return $this->renderSuccess([
                    'order_status' => $res,
                    'order_id' => $order_no
                ]);
            }
            /*if($divide){
                //开始分账 -- 待开发
            }*/
            $order['pay_status'] = 20;// 支付状态
            // 创建订单
            $model = new OrderModel;
            if (!$model->add($order)) {
    			$error = $model->getError() ?: '订单创建失败';
    			return $this->renderError($error);  
            }
            $order_detail = OrderModel::detail($model['order_id']);
            $Card = new CartModel($this->user['user_id'],$this->shop_id);
		    $Card->clearAll();
		    Cache::delete($order_no);
		    Device::push($this->shop_id,'new');//新订单提醒
            Device::print($order_detail);//打印订单
            sand_new_order_msg($order_detail);//发送模板消息 - 使用公众号
		    return $this->renderSuccess([
                'order_status' => $res,
                'order_id' => $model->order_id
            ]);
        }
        return $this->renderSuccess([
            'order_status' => 'ERROR'
        ]);
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
	
    

    /**
     * 取消订单
     */
    public function cancel($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->cancel()) {
            return $this->renderMsg('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

}
